import numpy as np
class PCA:
    def fit(self, data, low_dim):
        """
        参数：
        data: 待降维数据
        low_dim: 降维后的维度
        """
        #数据中心化
        mean_values = np.mean(data,axis=0)
        data_centered = data - mean_values
        #计算数据样本的协方差矩阵
        cov_data = np.cov(data_centered,rowvar=0)
        #对协方差矩阵进行特征分解
        eig_values, eig_vects = np.linalg.eig(cov_data)
        #对特征值进行排序,从大到小
        eig_values_sort = np.argsort(-eig_values)
        #选取前low_dim个特征值
        index = eig_values_sort[:low_dim]
        #选取前low_dim个特征值对应的特征向量
        select_eig_vects = eig_vects[:,index]
        #将原始数据data映射到低维空间data_low
        data_low = np.dot(data_centered,select_eig_vects)
        return data_low

import numpy as np
import matplotlib.pyplot as plt
def drawPoints(dataset1,dataset2):
    fig = plt.figure()
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    ax1.scatter(dataset1[:,0],dataset1[:,1],marker='s',s=40,color='red')
    dataset2 = np.array(dataset2)
    ax2.scatter(dataset2[:,0],dataset2[:,1],s=40,color='blue')
from sklearn.datasets import load_breast_cancer
cancer_data = load_breast_cancer()
data = cancer_data['data']
y = cancer_data['target']
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
data = scaler.fit_transform(data)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
x1 = np.argwhere(cancer_data['feature_names']=='mean symmetry')[0][0]
x2 = np.argwhere(cancer_data['feature_names']=='worst smoothness')[0][0]
x = data[:,[x1,x2]]
ax1.scatter(x[:,0],x[:,1],c=y,s=40,cmap=plt.cm.Spectral)
pca = PCA()
data_low = pca.fit(data,low_dim=2)
ax2.scatter(data_low[:,0],data_low[:,1],c=y,s=40,cmap=plt.cm.Spectral)
plt.show()